redis.replicate_commands()

local key = KEYS[1]
local ttl = tonumber(ARGV[1])
local max = tonumber(ARGV[2])

local time = redis.call('time')
local now = tonumber(time[1]) * 1000 + tonumber(time[2]) / 1000
local expired = now - ttl

redis.call('zremrangebyscore', key, 0, expired)

local current = tonumber(redis.call('zcard', key))
local next = current + 1

if next > max then
    return tostring(0);
else
    redis.call("zadd", key, now, now)
    redis.call("pexpire", key, ttl)
    return tostring(next)
end
